package com.markus.code.图.图1;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;

/**
 * Author:markusZhang
 * Date:Create in 2020/8/19 12:55
 * todo: 最小生成树 k算法
 */
public class GraphK {
    public Set<Edge> graphK(Graph graph){
        PriorityQueue<Edge> priorityQueue = new PriorityQueue<>(new MyComparator());
        HashSet<Edge> set = new HashSet<>();
        for (Edge edge : graph.edges) {
            priorityQueue.add(edge);
        }
        UnionAndSet uas = new UnionAndSet(new ArrayList<>(graph.nodes.values()));
        while(!priorityQueue.isEmpty()){
            Edge min = priorityQueue.poll();
            Node fromNode = min.from;
            Node toNode = min.to;
            if (!uas.isSameSet(fromNode,toNode)){
                uas.union(fromNode,toNode);
                set.add(min);
            }
        }
        return set;
    }
}
